package com.supersystem.utils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.util.HtmlUtils;

public class StringUtil extends StringUtils {

    private final static Log log = LogFactory.getLog(StringUtil.class);

    /**
     * use MD5 algorithm to digest the content, the returned result will be a BASE-64 based string.
     *
     * @param salt
     * @param content
     * @return
     */
    public static String digestToStringByMD5(String salt, String content) {
        byte[] bytes = digestToBytesByMD5(salt, content);
        return new String(Base64.encodeBase64(bytes));
    }

    /**
     * use MD5 algorithm to digest the content
     *
     * @param salt
     * @param content
     * @return
     */
    public static byte[] digestToBytesByMD5(String salt, String content) {
        MessageDigest nd = null;
        try {
            nd = MessageDigest.getInstance("MD5");
            if (StringUtils.isNotBlank(salt)) {
                content += "_" + salt;
            }
            return nd.digest(content.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalStateException(e);
        } catch (UnsupportedEncodingException e) {
            throw new IllegalStateException(e);
        }
    }

    /**
     * use MD5 algorithm to digest the content
     *
     * @param salt
     * @param content
     * @return
     */
    public static byte[] digestToBytesByMD5(Object obj) {
        MessageDigest nd = null;
        try {
            String content = ToStringBuilder.reflectionToString(obj) + "_" + obj.hashCode();
            nd = MessageDigest.getInstance("MD5");
            return nd.digest(content.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalStateException(e);
        } catch (UnsupportedEncodingException e) {
            throw new IllegalStateException(e);
        }
    }

    /**
     * <li>方法描述：covert blank string to "&#160;"</li>
     *
     * @param s
     * @return
     * @date Nov 6, 2010
     */
    public static String trimToHtmlBlank(String s) {
        return trimToSpecial(s, "&#160;");
    }

    /**
     * <li>方法描述：将空字符串转化为“”</li>
     *
     * @param s
     * @return
     * 
     * @date Nov 24, 2010
     */
    public static String trimToBlank(String s) {
        return trimToSpecial(s, "");
    }

    /**
     * <li>方法描述：将空字符串转化为指定字符</li>
     *
     * @param s
     * @param c
     * @return
     * @date Nov 24, 2010
     */
    public static String trimToSpecial(String s, String c) {
        return (StringUtils.isNotBlank(s) ? HtmlUtils.htmlEscape(s) : c);
    }

    /**
     * <li>方法描述：将空字符串转换为连字符</li>
     *
     * @param s
     * @return
     * @date Nov 24, 2010
     */
    public static String trimToHyphen(String s) {
        return trimToSpecial(s, "-");
    }

    /**
     * <li>方法描述：去掉内容里面的标签语言中的标签"<"和">"之间的内容</li>
     *
     * @param content
     * @return
     * @author 罗业刚
     */
    public static String dropMarkLanguageTags(String content) {
        if (isNotEmpty(content)) {
            // 去掉所有html元素,
            String str = content.replaceAll("\\&[a-zA-Z]{1,10};", "").replaceAll("<[^>]*>", "");
            return str.replaceAll("[(/>)<]", "");
        }
        return content;
    }

    public static boolean isNotEmpty(String s) {
        return s != null && !"".equals(s);
    }

    public static boolean isEmpty(String s) {
        return s == null || "".equals(s);
    }
    
    /**
     * 处理传入的参数，如果为空，则返回“”字符
     * @param param
     * @return
     */
    public static String parseParameterToString(Object param){
    	if(null == param) return "";
    	return param.toString();
    }

    /**
     * <li>方法描述：截断字符串，超过指定长度用...代替</li>
     *
     * @param s
     * @param len
     * @return
     * 
     * @throws UnsupportedEncodingException
     * @date Jan 15, 2011
     */
    public static String splitString(final String s, final int len) throws UnsupportedEncodingException {
        return splitString(s, len, "...");
    }

    /**
     * <li>方法描述：按指定长度截断字符串，超过长度的字符串用指定字符串代替；一个汉字长度为2，一个字符长度为1</li>
     *
     * @param s
     * @param len
     * @param endStr
     * @return
     * @throws UnsupportedEncodingException
     * @date Jan 15, 2011
     */
    public static String splitString(final String s, final int len, final String endStr)
            throws UnsupportedEncodingException {
        if (StringUtils.isBlank(s))
            return "-";
        int charLen = 0;
        StringBuffer sb = new StringBuffer("");
        for (int i = 0; i < s.length(); i++) {
            if (s.substring(i, i + 1).getBytes("UTF-8").length == 3) {
                // 中文
                charLen += 2;
            } else if (s.substring(i, i + 1).getBytes("UTF-8").length == 1) {
                // 英文
                charLen += 1;
            }
            sb.append(s.substring(i, i + 1));
            if (charLen >= len && i < s.length() - 1) {
                sb.append(endStr);
                break;
            }
        }
        return sb.toString();
    }

    /**
     * <li>方法描述：计算字符串长度</li> <li>一个中文字长度为2，一个英文字符或数字长度为1</li>
     *
     * @author Erich Li
     * @Date May 26, 2011
     * @param s
     * @return
     */
    public static int calcCharLength(String s) {
        int charLen = 0;
        try {
            if (StringUtils.isNotBlank(s)) {
                for (int i = 0; i < s.length(); i++) {
                    if (s.substring(i, i + 1).getBytes("UTF-8").length == 3) {
                        // 中文
                        charLen += 2;
                    } else if (s.substring(i, i + 1).getBytes("UTF-8").length == 1) {
                        // 英文
                        charLen += 1;
                    }
                }
            }
        } catch (UnsupportedEncodingException e) {
            log.error(e.getMessage(), e);
        }
        return charLen;
    }

    /**
     * <li>方法描述：生成店铺的根url</li>
     *
     * @author Erich Li
     * @Date Feb 23, 2011
     * @param secondDir
     * @param memberId
     * @return
     */
    public static String formatShopBaseUrl(String secondDir, int memberId) {
        StringBuffer url = new StringBuffer("/shop/");
        if (StringUtils.isNotBlank(secondDir))
            url.append(secondDir);
        else {
            url.append("member").append(memberId);
        }
        url.append("/");
        return url.toString();
    }

    /**
     * <li>方法描述：生成店铺的公司简介url</li>
     *
     * @author Erich Li
     * @Date Feb 23, 2011
     * @param secondDir
     * @param memberId
     * @return
     */
    public static String formatCompanyUrl(String secondDir, int memberId) {
        StringBuffer url = new StringBuffer(formatShopBaseUrl(secondDir, memberId));
        url.append("index.html");
        return url.toString();
    }

    /**
     * <li>方法描述：生成挂单详情url</li>
     *
     * @author Erich Li
     * @Date Feb 23, 2011
     * @param secondDir
     * @param memberId
     * @param createTime
     * @param mboId
     * @return
     */
    public static String formatMboUrl(String secondDir, int memberId, Date createTime, int mboId) {
        StringBuffer url = new StringBuffer(formatShopBaseUrl(secondDir, memberId));
        url.append("mbo/");
        url.append(DateUtil.formateToSpecificString(createTime, "yyMMdd")).append("/").append(mboId).append(".html");
        return url.toString();
    }

    public static String unicode2String(String s) {
        if (StringUtils.isBlank(s))
            return s;
        String[] unicodeStr = s.split("%u");
        StringBuffer sb = new StringBuffer();
        if (unicodeStr != null) {
            char[] tmp = new char[1];
            for (int i = 0; i < unicodeStr.length; i++) {
                if (StringUtils.isNotBlank(unicodeStr[i])) {
                    int num = Integer.parseInt(unicodeStr[i], 16);
                    tmp[0] = (char) (~0 & (num));
                    sb.append(new String(tmp));
                }
            }
        }
        return sb.toString();
    }

    public static String urlDecode(String s) {
        if (StringUtils.isBlank(s))
            return s;
        try {
            s = URLDecoder.decode(s, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            log.error(e.getMessage(), e);
        }
        return s;
    }

    public static String getStringValue(Object obj, String defaultValue) {
        if (obj == null) {
            return defaultValue;
        }
        return obj.toString();
    }

    public static String convert2BigMoney(double eSender) {
        double NewMoney;
        int Index, len, flag;
        StringBuffer sbTemp = new StringBuffer(128);
        char[] p;
        String Number[] = {"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"};
        String MonetaryUnit[] = {"万", "仟", "佰", "拾", "亿", "仟", "佰", "拾", "万", "仟", "佰", "拾", "元", "角", "分"};
        NewMoney = Math.abs(eSender);
        DecimalFormat deciformat;
        deciformat = (DecimalFormat) DecimalFormat.getInstance();
        deciformat.applyPattern("#######");
        String m = java.lang.String.valueOf(deciformat.format(NewMoney * 100));
        int i;
        if ((i = m.indexOf('.')) != -1)
            m = m.substring(0, i);
        p = new char[m.length()];

        m.getChars(0, m.length(), p, 0);

        if (NewMoney > 100000000000.00) {
            return sbTemp.append("").toString();
        }
        if (NewMoney < 0.01) {
            return sbTemp.append("零").toString();
        }
        if (eSender < 0) {
            sbTemp.append("负");
        } else {
            sbTemp.append("");
        }
        flag = 1;
        len = p.length;

        for (Index = (15 - len); Index < 15; Index++) {
            if (p[Index - 15 + len] != '0') {
                sbTemp.append(Number[Integer.parseInt(String.valueOf(p[Index - 15 + len]))]).append(MonetaryUnit[Index]);
            } else {
                if (Index == 5) {
                    if ((p[Index - 14 + len] != '0') || (p[Index - 13 + len] != '0')) {
                        sbTemp.append(MonetaryUnit[Index + 3]);
                        flag = 0;
                    }

                } else {
                    if ((Index == 12) || ((Index == 8) && (flag == 1)) || (Index == 4)) {
                        sbTemp.append(MonetaryUnit[Index]);
                    }
                    if ((p[Index - 15 + len] != '0') && (Index != 14)) {
                        sbTemp.append(Number[Integer.parseInt(String.valueOf(p[Index - 15 + len]))]);
                    }
                    if (p[Index - 15 + len] == '0' && StringUtils.isNotBlank(sbTemp.toString())
                        && !sbTemp.toString().endsWith("零") && ((Index - 15 + len) != (m.length() - 3))) {
                        int k = Index - 15 + len;
                        while (k <= m.length() - 1) {
                            if (p[k] != '0') {
                                sbTemp.append("零");
                                break;
                            }
                            k++;
                        }
                    }
                }
            }
        }
        if (p[m.length() - 1] == '0') {
            sbTemp.append("整");
        }
        return sbTemp.toString();
    }

    public static String encodeAttachmentFilename(String userAgent, String originalName)
            throws UnsupportedEncodingException {
        if (userAgent != null && userAgent.indexOf("MSIE") >= 0) {
            // 见微软的知识库文章 KB816868,IE在处理 Response Header 的时候，对header的长度限制在150字节左右。
            // 而一个汉字编码成UTF-8是9个字节，那么17个字便是153个字节，所以会报错,而且不跟后缀也不对.
            int dot = originalName.indexOf(".");
            String subfix = dot >= 0 ? originalName.substring(dot) : "";
            originalName = dot >= 0 ? originalName.substring(0, dot) : originalName;
            originalName = URLEncoder.encode(originalName, "utf-8");
            if (originalName.length() > 140) {
                originalName = originalName.substring(0, 140);
            }
            originalName += subfix;
        } else {
            originalName = new String(originalName.getBytes("utf-8"), "iso8859-1");
        }
        return originalName;
    }

    /***
     *  过滤HTML标签
     * @param htmlStr
     * @return
     */
    public static String replaceHTML(String htmlStr){
        //正则表达式列表
        String[] regExTags = {"<(style|strong)[^>]*>|<\\/(style|strong)>",
                              "(<|&lt;)[^(>|&gt;)]+(>|&gt;)",
                              "<(table|tbody|tr|td|th)[^>]*>|<\\/(table|tbody|tr|td|th)>",
                              "<(div|blockquote|fieldset|legend)[^>]*>|<\\/(div|blockquote|fieldset|legend)>",
                              "<(font|i|u|h[1-9]|s)[^>]*>|<\\/(font|i|u|h[1-9]|s)>",
                              "<(meta|iframe|frame|span|tbody|layer)[^>]*>|<\\/(iframe|frame|meta|span|tbody|layer)>",
                              "<a[^>]*>|<\\/a>",
                              "<br[^>]*",
                              "<br>"
                              } ;
        for(int i = 0 ; i < regExTags.length ; i ++){
            htmlStr = fiterHtmlTag(htmlStr , regExTags[i]) ;
        }
        return htmlStr;
    }

    /***
     *按照正则表达式进行过虑HTML标签
     * @param htmlStr
     * @param regEx
     * @return
     */
    public static String fiterHtmlTag(String htmlStr , String regEx){
        Pattern p_html = Pattern.compile(regEx, Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
        Matcher m_html = p_html.matcher(htmlStr);
        return m_html.replaceAll("");
    }
    
    /**
     * 去掉以特定字符分割且重复的字符窜，比如123,234,123就要去掉123，只保留一个
     * @param str 原字符窜
     * @param split 分隔符
     * @return
     */
    public static String delRepeatString(String str,String split){
    	if(StringUtils.isBlank(str)) return "";
    	if(StringUtils.isBlank(split)) split = ",";
    	String[] a = str.split(split);
    	List<String> list = new LinkedList<String>();  
        for(int i = 0; i < a.length; i++) {  
            if(!list.contains(a[i])) {  
                list.add(a[i]);  
            }  
        }  
        String retResult = list.toString();
        return retResult.substring(1, retResult.length()-1);
    }
    
    /**
     * 去掉以特定字符分割且重复的字符窜，比如123,234,123就要去掉123，只保留一个
     * @param str 原字符窜,且分隔符为逗号
     * @return
     */
    public static String delRepeatString(String str){
    	return delRepeatString(str,",");
    }
    
    public static void main(String[] args) {
		System.out.println(delRepeatString("123,234,123,234,123,123,45,123456,1"));
	}
}
